import { defineStore } from 'pinia';
import { getToken, removeToken, setToken } from '../utils/token-utils';
import type { UserInfoState } from './interface';
import { ElMessage } from 'element-plus';
import { staticRoutes, allAsyncRoutes, anyRoutes } from '@/router/routes';
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/acl/index';
import router from '@/router/index';
import cloneDeep from 'lodash/cloneDeep';
/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */

const getFilteredAsyncRoutes = (asyncRoutes, permissionList) => {
  console.log(permissionList);
  return asyncRoutes?.filter((route) => {
    if (route.children && route.children.length > 0) {
      route.children = getFilteredAsyncRoutes(route.children, permissionList);
    }
    return permissionList.includes(route.name);
  });
};
export const useUserInfoStore = defineStore('userInfo', {
  state: (): UserInfoState => ({
    token: getToken() as string,
    name: '',
    avatar: '',
    menuRoutes: [],
  }),

  actions: {
    async login(username: string, password: string) {
      const { token } = await reqLogin({ username, password });
      setToken(token);
      this.token = token;
    },

    async getInfo() {
      const data = await reqUserInfo();
      this.name = data.name;
      this.avatar = data.avatar;
      const permissionList = getFilteredAsyncRoutes(
        cloneDeep(allAsyncRoutes),
        data.routes
      );
      permissionList.forEach((route) => {
        router?.addRoute(route);
      });
      this.menuRoutes = staticRoutes.concat(permissionList, anyRoutes);
    },

    async reset() {
      await reqLogOut();
      removeToken();
      this.token = '';
      this.name = '';
      this.avatar = '';
    },
  },
});
